package my.video.lib.view;

import java.io.File;

import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;


import my.video.lib.controller.Controller;
import my.video.lib.model.VideoFile;

class MyTableModelListener implements TableModelListener {
	  JTable table;
	  Controller controller;

	  MyTableModelListener(JTable table, Controller controller) {
	    this.table = table;
	    this.controller = controller;
	  }

	  public void tableChanged(TableModelEvent e) {
	    int firstRow = e.getFirstRow();
	    int lastRow = e.getLastRow();
	    int column = e.getColumn();

	    switch (e.getType()) {
	    case TableModelEvent.INSERT:
	      for (int row = firstRow; row <= lastRow; row++) {
	        System.out.println("added row: " + row);
	      }
	      break;
	    case TableModelEvent.UPDATE:
	      if (firstRow == TableModelEvent.HEADER_ROW) {
	        if (column == TableModelEvent.ALL_COLUMNS) {
	          System.out.println("A column was added");
	        } else {
	          System.out.println(column + "in header changed");
	        }
	      } else {
	        for (int row = firstRow; row <= lastRow; row++) {
	          if (column == TableModelEvent.ALL_COLUMNS) {
	            System.out.println("All columns have changed");
	          } else {
	        	// update database entries for the file
	            VideoFile oldFile = controller.getModel().getXmlPersistenceList().get(row);
	            String newPath = oldFile.getFilePath().replace(oldFile.getFileName(), (String) table.getModel().getValueAt(row, column));
	            oldFile.setFilePath(newPath);
	            oldFile.setFileName((String) table.getModel().getValueAt(row, column));
	            System.out.println(oldFile.getFile().renameTo(new File(newPath)));
	            controller.getModel().getXmlPersistenceList().set(row, oldFile);
	            controller.getModel().refreshTable();
	          }
	        }
	      }
	      break;
	    case TableModelEvent.DELETE:
	      for (int row = firstRow; row <= lastRow; row++) {
	        System.out.println("deleted row: " + row);
	      }
	      break;
	    }
	  }
	}